import Taro from "@tarojs/taro";
import { onUnmounted, ref, watch } from "vue";

const storage = {
  events: new Map(),
  get(key) {
    return Taro.getStorageSync(key);
  },
  set(key, value) {
    Taro.setStorageSync(key, value);

    Promise.resolve().then(() => {
      const events = storage.events.get(key);
      [...events]?.forEach((event) => {
        event?.(value);
      });
    });
  },

  on: (key, event) => {
    const events = storage.events.get(key) || new Set();
    events.add(event);
    storage.events.set(key, events);
  },
  off: (key, event) => {
    const events = storage.events.get(key);
    events?.delete(event);
  },
};

/**
 * 访问和修改Storage的反应是调用
 * @param key 
 * @param defaultValue 默认值，如果能get到值，defaultValue会被忽略
 * @returns 
 */
const useStorage = (key: string, defaultValue?: any) => {
  const data = ref(storage.get(key) || defaultValue);

  watch(
    data,
    (val) => {
      storage.set(key, val);
    },
    { deep: true }
  );

  const update = (value) => {
    if (value !== data.value) {
      data.value = value;
    }
  };

  if (defaultValue) {
    storage.set(key, data.value);
  }

  storage.on(key, update);
  onUnmounted(() => storage.off(key, update));
  return data;
};

export default useStorage;
